package tr.edu.metu.is.mega.client.core;

import tr.edu.metu.is.mega.client.resource.MEGAResources;

import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Helper class for download actions.
 */
public class DownloadHelper {

    private final static String CONTENT_DISPOSITION = "applicatian-octet";

    private final static String CONTENT_TYPE = "attachment";

    /**
     * Downloads file given in filePath.
     * 
     * @param filePath path of the file
     */
    public static void downloadFile(String filePath) {

        if (filePath == null || filePath.length() == 0) {
            return;
        }

        try {
            StringBuffer buffer = new StringBuffer();
            buffer.append("/downloadservlet?filepath=");
            buffer.append(URL.encode(filePath));
            buffer.append("&contenttype=");
            buffer.append(URL.encode(CONTENT_TYPE));
            buffer.append("&contenttype=");
            buffer.append(URL.encode(CONTENT_DISPOSITION));

            Frame frame = new Frame(buffer.toString());
            frame.setSize("0px", "0px");
            frame.setVisible(false);
            RootPanel panel = RootPanel.get("_gwt_downloadFrame");
            while (panel.getWidgetCount() > 0) {
                panel.remove(0);
            }
            panel.add(frame);
        } catch (Exception ex) {
            Info.display(MEGAResources.RESOURCEBUNDLE.alertError(), MEGAResources.RESOURCEBUNDLE.errorMessage());
        }
    }

}
